<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item prop="searchValue">
        <el-input
          style="width: 300px"
          v-model="queryParams.searchValue"
          placeholder="搜索市、区县名称"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item prop="shareFlag">
        <el-select v-model="queryParams.shareFlag" placeholder="全部类型" style="width: 117px">
          <el-option label="允许访问" value="1"></el-option>
          <el-option label="禁止访问" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="city">
        <el-select v-model="queryParams.city" placeholder="选择城市" style="width: 103px" @change="getCountyOptions">
          <el-option
            v-for="item in cityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="county">
        <el-select v-model="queryParams.county" placeholder="全部区县" style="width: 103px">
          <el-option
            v-for="item in countyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery" round style="width: 90px">查询</el-button>
        <!--        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>-->
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['manuscripts:source:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['manuscripts:source:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['manuscripts:source:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['manuscripts:source:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="sourceList" @selection-change="handleSelectionChange" stripe>
      <el-table-column label="市区县ID" align="center" prop="siteCode" />
      <el-table-column label="市区县名称" align="center" prop="siteFullname" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.shareFlag"
            style="color: #D01010"
            size="mini"
            type="text"
            @click="showForbidAccessDialog(scope.row.id, scope.row.shareFlag)"
            v-hasPermi="['manuscripts:source:edit']"
          ><svg-icon icon-class="prohibit"/><span style="margin-left: 5px;">禁止访问区县共享库</span></el-button>
          <el-button
            v-else
            style="color: #1EBC65"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="showAllowAccessDialog(scope.row.id, scope.row.shareFlag)"
            v-hasPermi="['manuscripts:source:edit']"
          >允许访问区县共享库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改来源站点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="源编码" prop="siteCode">
          <el-input v-model="form.siteCode" placeholder="请输入源编码" />
        </el-form-item>
        <el-form-item label="上级编码" prop="parentSiteCode">
          <el-input v-model="form.parentSiteCode" placeholder="请输入上级编码" />
        </el-form-item>
        <el-form-item label="源名称" prop="siteName">
          <el-input v-model="form.siteName" placeholder="请输入源名称" />
        </el-form-item>
        <el-form-item label="源全称" prop="siteFullname">
          <el-input v-model="form.siteFullname" placeholder="请输入源全称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="编辑员" prop="editor">
          <el-input v-model="form.editor" placeholder="请输入编辑员" />
        </el-form-item>
        <el-form-item label="积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="是否允许访问区县共享库">
          <el-select v-model="form.shareFlag" placeholder="请选择是否允许访问区县共享库">
            <el-option
              v-for="dict in shareFlagOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  禁止访问确认弹窗  -->
    <el-dialog
      :visible.sync="forbidAccessDialogVisible"
      width="310px"
      center>
      <p style="text-align: center">确定要禁止此市区县访问共享库？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="forbidAccessDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="forbidAccess">确 定</el-button>
      </span>
    </el-dialog>

    <!--  允许访问确认弹窗  -->
    <el-dialog
      :visible.sync="allowAccessDialogVisible"
      width="310px"
      center>
      <p style="text-align: center">确定要允许此市区县访问共享库？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allowAccessDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowAccess">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getAllAreaData } from "@/api/manuscripts/source";
  import { listSource, getSource, delSource, addSource, updateSource, exportSource } from "@/api/manuscripts/source";

  export default {
    name: "Source",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 来源站点表格数据
        sourceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否允许访问区县共享库字典
        shareFlagOptions: [],
        // 城市和区县选项数据
        areasData: [],
        // 城市下拉选项
        cityOptions: [],
        // 区县下拉选项
        countyOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          searchValue: undefined,
          shareFlag: undefined,
          city: undefined,
          county: undefined,
          siteCode: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          siteCode: [
            { required: true, message: "源编码不能为空", trigger: "blur" }
          ],
        },
        // 禁止访问确认弹窗
        forbidAccessDialogVisible: false,
        forbidAccessId: '',
        forbidAccessFlag: '',
        // 允许访问确认弹窗
        allowAccessDialogVisible: false,
        allowAccessId: '',
        allowAccessFlag: '',
      };
    },
    created() {
      this.getList();
      this.getAllAreas();
      // this.getDicts("int").then(response => {
      //   this.shareFlagOptions = response.data;
      // });
    },
    methods: {
      /** 查询来源站点列表 */
      getList() {
        this.loading = true;
        // 将city,county参数合并为sourceFrom
        this.queryParams.siteCode = this.queryParams.county || this.queryParams.city;
        listSource(this.queryParams).then(response => {
          this.sourceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      // 查询城市和区县选项数据
      getAllAreas() {
        getAllAreaData().then(response => {
          // {
          //   "510100-成都市": ["510100-全部区县", "510104-锦江区"],
          //   "510300-自贡市": ["510300-全部区县", "510302-自流井区"],
          //   ...
          // }
          this.areasData = response.data;
          // 构造城市选项数据
          Object.keys(this.areasData).forEach((item) => {
            this.cityOptions.push({
              value: item.split("-")[0],
              label: item.split("-")[1],
            })
          })
        })
      },

      // 城市change时获取对应的区县选项数据
      getCountyOptions(val) {
        let cityVals = [];
        this.countyOptions = [];
        this.queryParams.county = undefined;
        Object.keys(this.areasData).forEach((item) => {
          cityVals.push(item.split("-")[0]);
        });
        let cityIndex = cityVals.indexOf(val);
        let cityKey = this.cityOptions[cityIndex].value + "-" + this.cityOptions[cityIndex].label;
        this.areasData[cityKey].forEach((item) => {
          this.countyOptions.push({
            value: item.split("-")[0],
            label: item.split("-")[1],
          })
        });
      },

      // 显示禁止访问弹窗
      showForbidAccessDialog(id, flag) {
        this.forbidAccessDialogVisible = true;
        this.forbidAccessId = id;
        this.forbidAccessFlag = flag === 1 ? 0 : 1;
      },

      // 禁止访问
      forbidAccess() {
        updateSource({ id: this.forbidAccessId, shareFlag: this.forbidAccessFlag }).then(response => {
          if (response.code === 200) {
            this.msgSuccess("禁止访问成功");
            this.forbidAccessDialogVisible = false;
            this.getList();
          } else {
            this.msgError(response.msg);
          }
        })
      },

      // 显示允许访问弹窗
      showAllowAccessDialog(id, flag) {
        this.allowAccessDialogVisible = true;
        this.allowAccessId = id;
        this.allowAccessFlag = flag === 0 ? 1 : 0;
      },

      // 允许访问
      allowAccess() {
        updateSource({ id: this.allowAccessId, shareFlag: this.allowAccessFlag }).then(response => {
          if (response.code === 200) {
            this.msgSuccess("允许访问成功");
            this.allowAccessDialogVisible = false;
            this.getList();
          } else {
            this.msgError(response.msg);
          }
        })
      },

      // 是否允许访问区县共享库字典翻译
      shareFlagFormat(row, column) {
        return this.selectDictLabel(this.shareFlagOptions, row.shareFlag);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          siteCode: undefined,
          parentSiteCode: undefined,
          siteName: undefined,
          siteFullname: undefined,
          phone: undefined,
          editor: undefined,
          integral: undefined,
          shareFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加来源站点";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getSource(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改来源站点";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateSource(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addSource(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除来源站点编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSource(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有来源站点数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSource(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
